package net.jalbum.filters.components;

import java.awt.event.ActionEvent;
import java.awt.event.FocusEvent;

import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;

public class GammaSlider extends ExtendedSlider {
    
    private final static int PRECISION = 100;
	/**
	 * 
	 */
	private static final long serialVersionUID = -2122782364313322527L;
	protected double resultingGamma;
	protected final double gamma = 0.301029996;
	
	public GammaSlider() {
		super(JSlider.HORIZONTAL, -100, 100, 0);
	}

	public GammaSlider(int orientation) {
		super(orientation, -100, 100, 0);
		slider.setValue(-1);
		slider.setValue(0);
	}
	
	public void actionPerformed(ActionEvent e) {
		if(e.getSource()==textfield){
	   		readTextfieldValue();
		}else{
   			super.actionPerformed(e);
		}
		
	}

	private void readTextfieldValue() {
		try{
			double value = Double.parseDouble(textfield.getText());
			if (value<0){
				value=0;
			}else if(value>10){
				value=10;
			}
			this.resultingGamma=value;
			slider.setValue((int)Math.pow(Math.pow(200,1/gamma)*this.resultingGamma/10,gamma)-100);
			textfield.setText(Double.toString((int)(value*PRECISION)/(double)PRECISION));
		}catch(Exception ex){
			textfield.setText(Double.toString((int)(resultingGamma*PRECISION)/(double)PRECISION));
		}
	}
	
	public void stateChanged(ChangeEvent arg0) {
		if(arg0.getSource()==slider){
			resultingGamma = 10*Math.pow((slider.getValue()+100),1/gamma)/Math.pow(200, 1/gamma);
			textfield.setText(Double.toString((int)(resultingGamma*PRECISION)/(double)PRECISION));
			postActionEvent();
		}
		
	}

	public void reset() {
		slider.setValue(0);
	}
	
	public double getResultingGamma() {
		return resultingGamma;
	}

	public void setResultingGamma(double value) {
		this.resultingGamma = value;
	}

	public int getValue() {
		return (int)resultingGamma;
	}

	public void setValue(int value) {
		this.resultingGamma = value;
	}

	public void focusLost(FocusEvent e) {
		if(e.getSource()==textfield){
	   		readTextfieldValue();
		}
	}
	
}
